import serial
import sys

BAUDRATE = 9600

def create_file(file_name):
    file_handler = open("resources/" + file_name + ".csv", "a")
    file_handler.write("Red,Green,Blue,Clear\n")
    return file_handler

def measure(port, file_handler = None):
    port.write('M')
    m = port.readline()
    m = m.rstrip('\r\n')
    if (file_handler != None) :
        file_handler.write(m + '\n')
    print "RGBC values:", m
    
def calibrate(port):
    print "Hold up a white object in front of the sensor, then press any key to calibrate...\n"
    raw_input()
    port.write('C')
    print "Capacitors values:", port.readline()
    print "Integration values:", port.readline()
    measure(port)
    print "All values should be under 1000. If they're not, try calibrating again, or decreasing the ambient brightness somehow."
    print "Press \"C\" to calibrate again"
    
    
if __name__ == "__main__":
    try:
        index = sys.argv.index('-help')
        if (index > -1):
            print '''
Connects with arduino to collect information about a color, showing RGB color gathered by different RGB cap values.

 -m num_measurements
        set how many measurements will be performed
        this is an optional param
        default value is 10
     
 -p port_name
        set which serial port arduino is connected to
        this is an optional param
        default value is COM3
    
 -help
        shows help'''
        sys.exit(0)
    except ValueError:
        pass
        
            
    num_measurements = 10
    try:
        index = sys.argv.index('-m')
        if (index > -1):
            num_measurements = int(sys.argv[index + 1])
    except ValueError:
        pass
        
    port_name = "COM3"
    try:
        index = sys.argv.index('-p')
        if (index > -1):
            port_name = sys.argv[index + 1]
    except ValueError:
        pass

    port = serial.Serial(port_name, BAUDRATE)
    print "Connection opened."

    # Handshake
    port.write('A')
    print "Handshake completed"
    
    #calibrate(port);
    
    colors = ['R', 'G', 'B']
    
    while True:
        file_name = raw_input()
        
        if (len(file_name) == 1):
            cmd = file_name
          
            if (cmd == 'X'):
                break
            elif (cmd == 'D' or cmd == 'L'):
                port.write(cmd)
                continue
            elif (cmd == 'C'):
                calibrate(port)
            elif (cmd == 'M'):
                measure(port)                
            elif (cmd == 'I'):
                port.write('I')
                print "Capacitors values:", port.readline()
                print "Integration values:", port.readline()
        else:
            file_handler = create_file(file_name)
            
            for i in xrange(num_measurements):
                measure(port, file_handler)
                      
            file_handler.close()
            
            print "\aEnd"
        
    port.close()
